// component/clockin/index.ts

import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { store } from "../../store/index"
import { getHrzList, HrzClockin,HrzClockinList } from '../../api/clockin'
ComponentWithStore({
  storeBindings: {
    store: store,
    fields: ["signinName",],
    actions: {
      updateName: "updateName",
      updateId:"updateId",
      updateType:"updateType"
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    latitude: -1 as number,
    longitude: -1 as number,
    markers: [] as any,
    userInfo: {},
    isSuccess: false,
    isGps: true,
    address: '定位中...',
    companyList: [],
    show: false,
    list:[]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getLocation() {
      const _this = this
      wx.getLocation({
        type: 'gcj02',
        altitude: true,
        isHighAccuracy: true,
        highAccuracyExpireTime: 4000,
        async success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          _this.setData({
            latitude: latitude,
            longitude: longitude,
            markers: [{
              id: 1,
              latitude: res.latitude,
              longitude: res.longitude,
            }]
          })
          const address = await _this.reverseGeocode(res.longitude, res.latitude)
          _this.setData({
            address: address
          })
          _this.getHrzList(res.latitude, res.longitude)
          console.log(res.longitude, res.latitude)
          // const distance = getDistance(res.latitude,res.longitude)
        },
      })
    },
    checkLocationAuth() {
      let that = this
      wx.getSetting({
        success: (res) => {
          let authSetting = res.authSetting
          if (authSetting['scope.userLocation']) {
            that.getLocation()
          } else if (authSetting['scope.userLocation'] === false) {
            wx.showModal({
              title: '您未开启地理位置授权',
              content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting()
                }
              }
            })
          } else {
            wx.authorize({
              scope: 'scope.userLocation',
              success: () => {
                that.getLocation()
              },
              fail: () => {
                wx.showModal({
                  title: '您未开启地理位置授权',
                  content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting()
                    }
                  }
                })
              }
            })
          }
        }
      })
    },
    reverseGeocode(latitude: number, longitude: number) {
      const apiKey = 'YvSi5eCAVD6v3Z0OUeqjdF0oYQcnK7gt'; // 替换为你的百度地图API密钥（AK）
      const apiUrl = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${apiKey}&output=json&coordtype=wgs84ll&location=${longitude},${latitude}`;
      return new Promise((resolve, reject) => {
        wx.request({
          url: apiUrl,
          success: (res: any) => {
            if (res.data.status === 0) {
              const address = res.data.result.formatted_address;
              resolve(address)
              console.log('地址：', address);
              // 在这里处理地址信息，例如更新页面上的文本或执行其他操作
            } else {
              reject(res.data.message)
              // console.error('逆地址解析失败：', res.data.message);
            }
          },
          fail: (error) => {
            console.error('请求失败：', error);
          }
        });
      })

    },
    getDistance(lat1: string, lon1: string, lat2: string, lon2: string) {
      // console.log(lat1, lon1, lat1, lon2)
      const R = 6371e3; // 地球半径，单位：米
      const lat1Rad = lat1 * (Math.PI / 180); // 将纬度转换为弧度
      const lat2Rad = lat2 * (Math.PI / 180); // 将纬度转换为弧度
      const deltaLat = (lat2 - lat1) * (Math.PI / 180); // 计算纬度之差并转换为弧度
      const deltaLon = (lon2 - lon1) * (Math.PI / 180); // 计算经度之差并转换为弧度

      const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
        Math.cos(lat1Rad) * Math.cos(lat2Rad) *
        Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      // console.log(lat1, lon1, lat2, lon2)
      return R * c; // 返回两点之间的距离（以米为单位）
    },
    handleClockin() {
      store.updateName('测试站点')
    },
    getHrzList(latitude: number, longitude: number) {
      getHrzList(this.data.userInfo.comID).then((res) => {
        const list = res.data.data.filter((v) => {
          const distance = this.getDistance(latitude, longitude, v.latitude, v.longitude)
          return distance < 1000
          // console.log(this.getDistance(latitude,longitude,v.latitude,v.longitude))
        })
        // console.log(list)
        this.setData({
          companyList: list
        })
        console.log(res)
      })
    },
    handleClose() {
      this.setData({
        show: false
      })
    },
    onNoScope() {
      this.setData({
        show: true
      })
    },
    handlePicker(e: any) {
      const _this = this
      const { userInfo, companyList,latitude,longitude } = this.data
      const { type, id,name } = e.detail.value
      if (companyList.length == 0) {
        wx.showModal({
          title: '错误',
          content: '附近没有站点',
          confirmText: '重新定位',
          success(res) {
            if (res.confirm) {
              _this.checkLocationAuth();
            } else if (res.cancel) {
            }
          }
        })
      } else {
        HrzClockin(userInfo.comID, type, id, userInfo.userID, 1,longitude,latitude).then((res: any) => {
          if (res.data.code == 200) {
            this.setData({
              show: false,
              isSuccess:true
            })
            wx.showToast({
              title: '打卡成功'
            })
            store.updateName(name)
            store.updateId(id)
            store.updateType(type)
            this.getHrzClockinList()
            setTimeout(()=>{
              this.setData({
                isSuccess:false
              })
            },3000)
          } else {
            wx.showToast({
              title: '打卡失败',
              icon: 'error'
            })
          }
        })
      }

      console.log(e)
    },
    getHrzClockinList(){
      HrzClockinList(this.data.userInfo.comID,this.data.userInfo.userID).then((res:any)=>{
        this.setData({
          list:res.data.data
        })
      })
    }
  },
  pageLifetimes: {
    show: async function () {
      // 页面被展示
      this.checkLocationAuth();
      this.setData({
        userInfo: wx.getStorageSync("userInfo").data
      })
      this.getHrzClockinList()
      //  this.getHrzList();
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    },
  },
})